﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using CMN.Framework;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Normal_LenceneController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        /// <summary>
        /// 返回友情链接列表
        /// </summary>
        /// <returns>json</returns>
        public string List2()
        {

            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, MethodType.Get, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, MethodType.Get, 9, 1, DataType.Int);
            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex;
            qp.PageSize = pageSize;
         
            int recordNum = 0;

            IDataService<Normal_SearchContentEntity> Module_ArticleSv = ServiceBuilder.BuildNormal_SearchContentService();
            List<Normal_SearchContentEntity> module_articleList = Module_ArticleSv.List(qp, out recordNum);
            //AppLog.Write(string.Concat("索引读取成功", qp.PageIndex.ToString(), ";", qp.PageSize.ToString(), ";", module_articleList.Count.ToString()), AppLog.LogMessageType.Debug);
            LuceneHelper lucene = new LuceneHelper();
            if (qp.PageIndex == 1)
            {
                //lucene.DeleteAll();
            }
            lucene.CreateIndex(module_articleList);
            AppLog.Write(string.Concat("索引创建成功", qp.PageIndex.ToString(), ";", qp.PageSize.ToString(), ";", module_articleList.Count.ToString()), AppLog.LogMessageType.Debug);
            if ((qp.PageIndex * qp.PageSize) > recordNum)
            {
                lucene.Optimize();
                returnJson = string.Concat("{totalPorperty:", recordNum, ",message:\"已经添加完毕\"}");

            }
            else
                returnJson = string.Concat("{totalPorperty:", recordNum, ",message:\"共有", recordNum.ToString(), ",已经添加", (qp.PageIndex * pageSize - pageSize).ToString(), "--", (qp.PageIndex * pageSize).ToString(), "\"}");
            return returnJson;

        }

        /// <summary>
        /// 返回友情链接列表
        /// </summary>
        /// <returns>json</returns>
        public string List()
        {

            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, MethodType.Get, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, MethodType.Get, 9, 1, DataType.Int);
            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex;
            qp.PageSize = pageSize;
            qp.TableName = " Module_Article a left join  Module_ArticleContent c on a.Id=c.Id";
            qp.ReturnFields = " a.* ,c.TextContent ";
            qp.Orderfld = " a.id desc ";
            qp.NotInRowName = "a.Id";
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
            List<Module_ArticleEntity> module_articleList = Module_ArticleSv.List(qp, out recordNum);
            List<Normal_TagsEntity> tagsList = new List<Normal_TagsEntity>();
            foreach (Module_ArticleEntity article in module_articleList)
            {
                tagsList = TagList(article.Tags);
                for (int i = 0; i < tagsList.Count; i++)
                {

                    if (i == tagsList.Count)
                        article.Tags = string.Concat(article.Tags, tagsList[i].TagName);
                    else
                        article.Tags = string.Concat(article.Tags, tagsList[i].TagName, ",");

                }
            }
            AppLog.Write(string.Concat("索引读取成功", qp.PageIndex.ToString(), ";", qp.PageSize.ToString(), ";", module_articleList.Count.ToString()), AppLog.LogMessageType.Debug);
            LuceneHelper lucene = new LuceneHelper();
            if (qp.PageIndex == 1)
            {
                lucene.DeleteAll();
            }
            if (recordNum > 1)
                lucene.CreateIndex(module_articleList);
            AppLog.Write(string.Concat("索引创建成功", qp.PageIndex.ToString(), ";", qp.PageSize.ToString(), ";", module_articleList.Count.ToString()), AppLog.LogMessageType.Debug);
            if ((qp.PageIndex * qp.PageSize) > recordNum)
            {
                lucene.Optimize();
                returnJson = string.Concat("{totalPorperty:", recordNum, ",message:\"已经添加完毕\"}");

            }
            else
                returnJson = string.Concat("{totalPorperty:", recordNum, ",message:\"共有", recordNum.ToString(), ",已经添加", (qp.PageIndex * pageSize - pageSize).ToString(), "--", (qp.PageIndex * pageSize).ToString(), "\"}");
            return returnJson;

        }
        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="showNum"></param>
        /// <param name="cacheTime"></param>
        /// <returns></returns>
        public List<Normal_TagsEntity> TagList(string strId)
        {

            List<Normal_TagsEntity> noticeList = MvcWebCacheManager.GetNormal_TagsList();
            List<Normal_TagsEntity> rnoticeList = new List<Normal_TagsEntity>();
            string[] idList = strId.Split(',');
            for (int i = 0; i < idList.Length; i++)
            {
                foreach (Normal_TagsEntity tag in noticeList)
                {

                    if (tag.Id.ToString() == idList[i])
                    {
                        rnoticeList.Add(tag);
                        break;
                    }

                }
            }
            return rnoticeList;
        }

        /// <summary>
        /// 查看友情链接 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Normal_LinkEntity> Normal_LinkSv = ServiceBuilder.BuildNormal_LinkService();
            int intId=Utils.StringToInt(actionId,0);
            Normal_LinkEntity normal_link = Normal_LinkSv.Look(intId);
            if (normal_link != null)
            {
                IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                jsDataConvert.DateTimeFormat = "yyyy-MM-dd hh:mm:ss";
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(normal_link, Formatting.Indented, jsDataConvert), "}");
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 优化索引
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {

            LuceneHelper lucene = new LuceneHelper();


            if (lucene.Optimize())
            {
                returnJson = "{success:'true',message:\"已经优化完毕\"}";
            }
            else
                returnJson = "{success:'true',message:\"优化失败\"}";


            return returnJson;
        }

        /// <summary>
        /// 新增友情链接
        /// </summary>
        /// <returns>json</returns>
        public string Insert()
        {
            Normal_LinkEntity normal_link = new Normal_LinkEntity();
            normal_link.DataTable_Action = DataTableAction.Insert;
            normal_link.Title = (String)Utils.GetQueryAndFormString("Title", this, 50,  1 , DataType.Str);
            normal_link.Url = (String)Utils.GetQueryAndFormString("Url", this, 150,  1 , DataType.Str);
            normal_link.ImgPath = (String)Utils.GetQueryAndFormString("ImgPath", this, 150,  0, DataType.Str);
            normal_link.Info = (String)Utils.GetQueryAndFormString("Info", this, 250,  0, DataType.Str);
            normal_link.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10,  0, DataType.Int);
            normal_link.State = (bool)Utils.GetQueryAndFormString("State", this, 6,  1 , DataType.Bool);
            normal_link.Type = (Int32)Utils.GetQueryAndFormString("Type", this, 10,  0, DataType.Int);
            normal_link.AddDatetime = DateTime.Now;
            normal_link.EndDatetime = (DateTime?)Utils.GetQueryAndFormString("EndDatetime", this, 23,  0, DataType.Dat);
            normal_link.ShowType = (String)Utils.GetQueryAndFormString("ShowType", this, 50, 0, DataType.Str);
           IDataService<Normal_LinkEntity> Normal_LinkSv = ServiceBuilder.BuildNormal_LinkService();
           if (Normal_LinkSv.Insert(normal_link) == "")
            {
                returnJson = "{success:'true'}";
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 删除友情链接
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Normal_LinkEntity normal_link = new Normal_LinkEntity();
                normal_link.Id = intId;
                IDataService<Normal_LinkEntity> Normal_LinkSv = ServiceBuilder.BuildNormal_LinkService();
                if (Normal_LinkSv.Delete(normal_link) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除友情链接
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Normal_LinkEntity> Normal_LinkSv = ServiceBuilder.BuildNormal_LinkService();
                if (Normal_LinkSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
